<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/6/20
 * Time: 14:42
 */

namespace Biz\module\Classes\adm;

use Biz\cache\Coupon as cCoupon;
use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\model\activity\CouponRecord as mCouponRecord;
use Biz\model\activity\CouponSend as mCouponSend;
use Biz\model\admin\AdminUser as mAdminUser;
use Biz\model\ShopBasicInfo;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\ShopInfo;
use Doraemon\service\User as sUser;
use Medoo\Medoo;
use Doraemon\cache\Queue;
use Doraemon\tools\ImgUrl as tImgUrl;

class Coupon extends \Biz\module\Classes\Coupon
{
    use _Async;

    public static function getCouponConfigSearchList($where, $limit)
    {
    	$search['assume'] = $where['assume'];
		$search['title[~]'] = $where['title[~]'];
    	if ($where['assume'] == mCouponConfig::COUPON_ASSUME_SHOP && $where['keyword']) {
    		if ($where['search_type'] == 1) {
    			$search['shop_id'] = $where['keyword'];
			} else if ($where['search_type'] == 2) {
    			$shopInfos = ShopBasicInfo::select('*', ['name[~]' => $where['keyword']]);
    			if ($shopInfos) {
					$search['shop_id'] = array_column($shopInfos, 'shop_id');
				} else {
    				return [[], 0];
				}
			}
		}
    	if ($where['status']) {
    		if ($where['status'] == 1) {
    			$search['stop_time[<]'] = date("Y-m-d H:i:s");
                $search['type_time[!]'] = mCouponConfig::TYPE_TIME_RELATIVELY;
			} else if ($where['status'] == 2) {
				$search['OR']['start_time[<]'] = date("Y-m-d H:i:s");
				$search['OR']['stop_time[>]'] = date("Y-m-d H:i:s");
                $search['OR']['type_time'] = mCouponConfig::TYPE_TIME_RELATIVELY;
			}
		}
        $list = mCouponConfig::getCouponList($search, $limit);
    	$shopInfos = ShopInfo::getShopInfoList(array_column($list, 'shop_id'));
    	foreach ($list as $k => $item) {
    		$list[$k]['shop_name'] = isset($shopInfos[$item['shop_id']]) ? $shopInfos[$item['shop_id']]['name'] : '';
		}

    	$count = mCouponConfig::count($search);

    	return [$list, $count];
    }

    public static function sendToUser($adminUid, $couponId, $uidList, $reason, $sysMsgData = [])
    {

        //插入数据到coupon_send
        $nowTime = time();

        $uidToList = array_filter(explode("\n", $uidList));

        mCouponSend::insert([
            'coupon_id'    => $couponId,
            'uid_list'     => implode(',', $uidToList),
            'reason'       => $reason,
            'img_url'      => isset($sysMsgData['img_url'])?$sysMsgData['img_url']:'',
            'title'        => isset($sysMsgData['title'])?$sysMsgData['title']:'',
            'content'      => isset($sysMsgData['content'])?$sysMsgData['content']:'',
            'redirect_url' => isset($sysMsgData['redirect_url'])?$sysMsgData['redirect_url']:'',
            'status'       => mCouponSend::STATUS_UNSEND,
            'addtime'=>date('Y-m-d H:i:s'),
            'admin_uid'    => $adminUid
        ]);

        $pushId = mCouponSend::id();

        if(empty($pushId)){
            throw new \Exception('优惠券发放失败');
        }


        //用户UID列表
        $uidList = array_filter($uidToList);

        //获取优惠券信息
        $couponConfig = mCouponConfig::getCouponInfo($couponId);

        //初始化发券数
        if ($couponConfig['sent_count'] == -1) {
            mCouponConfig::update(['sent_count' => 0], ['coupon_id' => $couponId]);
        }

        //开始启动分批发送
        foreach ($uidList as $uid) {
            self::_async($pushId, $uid, $couponConfig, $sysMsgData, $nowTime);
        }

    }

    public static function _async_SendToUser($pushId, $uid, $couponConfig, $sysMsgData, $nowTime)
    {

        //启动事物
        $result = mCouponSend::action(function () use ($pushId, $uid, $couponConfig, $sysMsgData, $nowTime) {
			$title = '';
        	if ($couponConfig['type'] == mCouponConfig::COUPON_TYPE_DISCOVER) {
				$title = sprintf("满%d减%d", $couponConfig['full_amount'], $couponConfig['detract_amount']);
			} elseif($couponConfig['type'] == mCouponConfig::COUPON_TYPE_DISCOUNT) {
				$title =  sprintf("满%d打%s折", $couponConfig['full_amount'], floatval($couponConfig['discount_level']));
			}

            $data = [
                'shop_id'        => 0,
				'type'    => $couponConfig['type'],
                'assume'         => mCouponConfig::COUPON_ASSUME_HHZ,
                'receive_way'    => mCouponRecord::RECEIVE_WAY_ADMIN,
                'title'          => $title,
                'full_amount'    => $couponConfig['full_amount'],
				'discount_level' => $couponConfig['discount_level'],
                'detract_amount' => $couponConfig['detract_amount'],
                'status'         => mCouponRecord::COUPON_STATUS_UNUSED
            ];
            if ($couponConfig['type_time'] == mCouponConfig::TYPE_TIME_RELATIVELY) {
                $relativeSecond = $couponConfig['relative_days'] * 86400;

                $data['start_time'] = date('Y-m-d H:i:s', $nowTime);
                $data['stop_time'] = date('Y-m-d 23:59:59', $nowTime + $relativeSecond);
            } else {

                $data['start_time'] = $couponConfig['start_time'];
                $data['stop_time'] = $couponConfig['stop_time'];
            }

            //插入优惠券记录
            mCouponRecord::insertCoupon($uid, $couponConfig['coupon_id'], $data);

            $couponVid = mCouponRecord::id();

            //更新发送的coupon_vid记录
            $couponSend = mCouponSend::select_master(['uid_list', 'coupon_vid_list'], Medoo::raw(' where push_id=:push_id for update', [':push_id' => $pushId]));

            //更新发券数和领券数，以及进度
            $data = ['coupon_vid_list' => trim($couponSend[0]['coupon_vid_list'] . ',' . $couponVid, ',')];

            //发送的总coupon数    指定的用户总数
            $couponVidCount = count(explode(',', $data['coupon_vid_list']));
            $uidCount = count(explode(',', $couponSend[0]['uid_list']));
            if ($couponVidCount != $uidCount) {
                $data['status'] = mCouponSend::STATUS_SENDING;
            } else {
                $data['status'] = mCouponSend::STATUS_SEND;
            }

            mCouponSend::update($data, ['push_id' => $pushId]);

            mCouponConfig::update(['received_count[+]' => 1, 'sent_count[+]' => 1], ['coupon_id' => $couponConfig['coupon_id']]);

            return true;
        });

        if ($result !== false) {

            if(empty($sysMsgData)){
                return true;
            }

            if(empty($sysMsgData['title']) && empty($sysMsgData['content']) && empty($sysMsgData['img_url'])){
                return true;
            }
            //发送系统消息
            Queue::insertQueue('queue/Sysmsg/Send',
                [
                    'msgCode'   => 0,
                    'to_uid'    => $uid,
                    'msgParams' => [
                        'title'  => $sysMsgData['title'],
                        'link'   => $sysMsgData['redirect_url'],
                        'img'    => !empty($sysMsgData['img_url'])?tImgUrl::getUrl(tImgUrl::APPTYPE_BIZ, $sysMsgData['img_url'], tImgUrl::IMAGE_SIZE_ORI_NPHONE):'',
                        'detail' => $sysMsgData['content']
                    ]
                ], Queue::QUEUE_DORAEMON);
        }


    }

    public static function sendList($couponId){
        $list = mCouponSend::select('*',['coupon_id'=>$couponId,'ORDER'=>['push_id'=>'DESC']]);

        $adminUidList = array_column($list,'admin_uid');
        $adminUserList = mAdminUser::getAdminList($adminUidList);

        $list = array_map(function ($v) use ($adminUserList){
            mCouponSend::formatInfo($v);

            $v['admin_user'] = [
                'admin_uid'=>$v['admin_uid'],
                'admin_name'=>$adminUserList[$v['admin_uid']]['name']
            ];
            return $v;
        },$list);


        return $list;
    }
    public static function sendUserList($pushId){
        $info = mCouponSend::get(['uid_list'],['push_id'=>$pushId]);

        $userIdList = explode(',',$info['uid_list']);

        $list = sUser::getUserInfoByIds($userIdList);

        return $list;
    }

}